<?php
if (!defined('BASEPATH'))
    exit('No direct script access allowed');

//define field to generate form
if (!function_exists('zip')) {
    function zip($sourcefolder)
    {
        $fileNameArr = explode('/', $sourcefolder);
        $fileName = array_pop($fileNameArr);

        $zipfilename  = $fileName.".zip"; // Default: "myarchive.zip"
        $timeout      = 5000           ; // Default: 5000

        // instantate an iterator (before creating the zip archive, just
        // in case the zip file is created inside the source folder)
        // and traverse the directory to get the file list.
        $dirlist = new RecursiveDirectoryIterator($sourcefolder);
        $filelist = new RecursiveIteratorIterator($dirlist);

        // set script timeout value
        ini_set('max_execution_time', $timeout);

        // instantate object
        $zip = new ZipArchive();

        // create and open the archive
        if ($zip->open(dirname($sourcefolder)."/$zipfilename", ZipArchive::CREATE) !== TRUE) {
            die ("Could not open archive");
        }

        // add each file in the file list to the archive
        foreach ($filelist as $key=>$value) {
            $fileNameArr = explode('/', $key);
            $fileName = array_pop($fileNameArr);

            if ($fileName != '.' && $fileName != '..') {
                $zip->addFile(realpath($key), date('d.m.Y').'/'.$fileName) or die ("ERROR: Could not add file: $key");
            }
        }

        // close the archive
        $zip->close();
        $filepath = dirname($sourcefolder).'/';
        $filename = date('d.m.Y').'.zip';


        header("Pragma: public");
        header("Expires: 0");
        header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Cache-Control: public");
        header("Content-Description: File Transfer");
    //        header("Content-type: application/octet-stream");
        header("Content-type: application/zip");
        header("Content-Disposition: attachment; filename=\"".$zipfilename."\"");
        header("Content-Transfer-Encoding: binary");
        header("Content-Length: ".filesize($filepath.$zipfilename));
        ob_end_flush();
        @readfile($filepath.$zipfilename);
    }
}

